package org.zhao.nettydemos.echoServer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: xiaohui.zhao
 * @Date: 2021/9/15 16:08
 * @Description:
 *
 * ChannelHandler.Sharable 表示handler实例可以被多个通道安全地共享
 */
@ChannelHandler.Sharable
@Slf4j
public class NettyEchoServerHandler extends ChannelInboundHandlerAdapter {

    public static final NettyEchoServerHandler INSTANCE = new NettyEchoServerHandler();

    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg)throws Exception{
        ByteBuf in = (ByteBuf) msg;
        log.info("msg type : "+ (in.hasArray()?"堆内存":"直接内存"));
        int len = in.readableBytes();
        byte[] arr = new byte[len];
        in.getBytes(0,arr);
        log.info("Server received: "+new String (arr,"UTF-8"));

        // 写回数据 异步任务
        ChannelFuture channelFuture = ctx.writeAndFlush(msg);
        channelFuture.addListener((ChannelFutureListener) -> {
            log.info("写回后 ， msg.refCnt: "+((ByteBuf) msg).refCnt());
        });
    }

}